package com.sdr.webCamera;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.company.PlaySDK.IPlaySDK;
import com.dh.DpsdkCore.Get_RecordStream_File_Info_t;
import com.dh.DpsdkCore.Get_RecordStream_Time_Info_t;
import com.dh.DpsdkCore.IDpsdkCore;
import com.dh.DpsdkCore.Query_Record_Info_t;
import com.dh.DpsdkCore.Record_Info_t;
import com.dh.DpsdkCore.Return_Value_Info_t;
import com.dh.DpsdkCore.fMediaDataCallback;

import org.apache.cordova.CordovaActivity;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;

public class BackPlayActivity extends Activity {
    //根view
    private LinearLayout mRootView;

    private TextView tv_ret;
    private TextView et_cam_id;
    private Button bt_query_video;
    private Button bt_playback_file;
    private Button bt_playback_time;
    private Button bt_playback_close;
    //		private DatePicker dp_start_date;
//		private DatePicker dp_end_date;
//		private TimePicker tp_start_time;
//		private TimePicker tp_end_time;
    //private ListView lvRecord;
    //private RecordInfoListView mRecordList = null;
    private TextView chooseStartTxt;
    private TextView chooseEndTxt;
    private Button chooseStartBtn;
    private Button chooseEndBtn;
    private DatePicker dp;
    private TimePicker tp;
    private Calendar startCalendar;
    private Calendar endCalendar;

    Get_RecordStream_File_Info_t m_RecordFileInfo = new Get_RecordStream_File_Info_t();
    Return_Value_Info_t m_nPlaybackSeq = new Return_Value_Info_t();
    SurfaceView m_svPlayer = null;
    private int m_nRecordSource = 0;
    private int m_pDLLHandle = 0;
    private int m_nPort = 0;

    //媒体数据回调
    private fMediaDataCallback fm;
    private String channelId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getApplication().getResources()
                .getIdentifier("fragment_playback", "layout", getApplication().getPackageName()));
        startCalendar = Calendar.getInstance();
        endCalendar = Calendar.getInstance();
        m_pDLLHandle = webCameraManager.getDpsdkHandle();

        // 查找控件
        findViews();
        // 设置监听器
        setListener();
        // 设置默认时间 
        setTextDate();
        makeSpinner();

        et_cam_id.setText(getIntent().getStringExtra("channelName"));
        channelId = getIntent().getStringExtra("channelId");
        m_nPort = IPlaySDK.PLAYGetFreePort();
        SurfaceHolder holder = m_svPlayer.getHolder();
        holder.addCallback(new Callback() {
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d("xss", "surfaceCreated");
                IPlaySDK.InitSurface(m_nPort, m_svPlayer);
            }

            public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                       int height) {
                Log.d("xss", "surfaceChanged");
            }

            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.d("xss", "surfaceDestroyed");
            }
        });
        fm = new fMediaDataCallback() {

            @Override
            public void invoke(int nPDLLHandle, int nSeq, int nMediaType,
                               byte[] szNodeId, int nParamVal, byte[] szData, int nDataLen) {

                int ret = IPlaySDK.PLAYInputData(m_nPort, szData, nDataLen);
                if (ret == 0) {
                    Log.e("xss", "playing success=" + nSeq + " package size=" + nDataLen);
                } else {
                    Log.e("xss", "playing failed=" + nSeq + " package size=" + nDataLen);
                }
            }
        };
    }


    @Override
    protected void onResume() {
        super.onResume();
        setTextDate();
    }


    private void findViews() {
        mRootView = (LinearLayout) findViewById(getResources()
                .getIdentifier("main_fragment_playback", "id",getPackageName()));
        tv_ret = (TextView) findViewById(getResources()
                .getIdentifier("tv_excute_result", "id",getPackageName()));
        et_cam_id = (TextView) findViewById(getResources()
                .getIdentifier("et_cam_id", "id",getPackageName()));
        bt_query_video = (Button) findViewById(getResources()
                .getIdentifier("bt_query_video", "id",getPackageName()));
        bt_playback_file = (Button) findViewById(getResources()
                .getIdentifier("bt_playback_by_file", "id",getPackageName()));
        bt_playback_time = (Button) findViewById(getResources()
                .getIdentifier("bt_playback_by_time", "id",getPackageName()));
        bt_playback_close = (Button) findViewById(getResources()
                .getIdentifier("bt_close_playback", "id",getPackageName()));
  /*      dp_start_date = (DatePicker)findViewById(R.id.dp_start_date);
        dp_end_date = (DatePicker)findViewById(R.id.dp_end_date);
        tp_start_time = (TimePicker)findViewById(R.id.tp_start_time);
        tp_end_time = (TimePicker)findViewById(R.id.tp_end_time);*/
        //lvRecord = (ListView)findViewById(R.id.lv_records);
        //mRecordList = new RecordInfoListView(getApplicationContext(), lvRecord);
        //选择时间
        chooseEndTxt = (TextView) findViewById(getResources()
                .getIdentifier("choose_end_time_txt", "id",getPackageName()));
        chooseStartTxt = (TextView) findViewById(getResources()
                .getIdentifier("choose_start_time_txt", "id",getPackageName()));
        chooseEndBtn = (Button) findViewById(getResources()
                .getIdentifier("choose_end_time_btn", "id",getPackageName()));
        chooseStartBtn = (Button) findViewById(getResources()
                .getIdentifier("choose_start_time_btn", "id",getPackageName()));
        m_svPlayer = (SurfaceView) findViewById(getResources()
                .getIdentifier("sv_player", "id",getPackageName()));

    }

    private void setTextDate() {
        /*Time date = new Time();
		chooseStartTxt.setText(String.valueOf(date.year) + "年" + String.valueOf(date.month) + "月" + String.valueOf(date.monthDay) + "日"
				+ String.valueOf(date.hour) + "时" + String.valueOf(date.minute) + "分" + String.valueOf(date.second) + "秒");*/
        Calendar c = Calendar.getInstance();
        chooseStartTxt.setText(String.valueOf(c.get(Calendar.YEAR)) + "年" + String.valueOf(c.get(Calendar.MONTH) + 1) + "月"
                + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "日" + "00" + "时" + "00" + "分");
        chooseEndTxt.setText(String.valueOf(c.get(Calendar.YEAR)) + "年" + String.valueOf(c.get(Calendar.MONTH) + 1) + "月"
                + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "日" + "23" + "时" + "59" + "分");

        startCalendar.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH),
                0, 0, 0);
        endCalendar.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH),
                23, 59, 0);

    }

    class chooseTimeListener implements OnClickListener {

        @Override
        public void onClick(final View v) {

            LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View vPopWindow = inflater.inflate(getResources()
                    .getIdentifier("popwindow_choose_time", "layout",getPackageName()), null, false);
            final PopupWindow popWindow = new PopupWindow(vPopWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT);

            vPopWindow.findViewById(getResources()
                .getIdentifier("finish_btn", "id",getPackageName())).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dp = (DatePicker) vPopWindow.findViewById(getResources()
                            .getIdentifier("datePicker1", "id",getPackageName()));
                    tp = (TimePicker) vPopWindow.findViewById(getResources()
                            .getIdentifier("timePicker1", "id",getPackageName()));
                    String year = String.valueOf(dp.getYear());
                    String month = String.valueOf(dp.getMonth() + 1);
                    String dayofmonth = String.valueOf(dp.getDayOfMonth());
                    String hour = String.valueOf(tp.getCurrentHour());
                    String minute = String.valueOf(tp.getCurrentMinute());
                    //判断点击的是开始还是结束按钮
                    if (v.getId() == chooseStartBtn.getId()) {
                        chooseStartTxt.setText(year + "年" + month + "月" + dayofmonth + "日" + hour + "时" + minute + "分");
                        startCalendar.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),
                                tp.getCurrentHour(), tp.getCurrentMinute(), 0);
                    } else {
                        chooseEndTxt.setText(year + "年" + month + "月" + dayofmonth + "日" + hour + "时" + minute + "分");
                        endCalendar.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),
                                tp.getCurrentHour(), tp.getCurrentMinute(), 0);
                    }
                    popWindow.dismiss();


                }
            });
            popWindow.showAtLocation(mRootView, Gravity.CENTER, 0, 0);
        }

    }

    private void setListener() {

        final Calendar c = Calendar.getInstance();
        //c.set(year, month, day, hourOfDay, minute, second)
        //选择日期控件
        chooseStartBtn.setOnClickListener(new chooseTimeListener());
        chooseEndBtn.setOnClickListener(new chooseTimeListener());

		/*chooseEndTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//Calendar c = Calendar.getInstance();
//				DatePickerDialog dpd = new DatePickerDialog(BackPlayActivity.this, new DatePickerDialog.OnDateSetListener() {
//					
//					@Override
//					public void onDateSet(DatePicker dp, int year, int month, int dayofmonth) {
//						
//						//chooseStartTxtTxt.setText(year + "年" + (month + 1)  + "月" + dayofmonth);
//						chooseEndTxt.setText(String.format("%4d年%02d月%02d日", year, month + 1, dayofmonth));
//					}
//				}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
//				dpd.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
//				dpd.show();
				TimePickerDialog dpd = new TimePickerDialog(BackPlayActivity.this, new TimePickerDialog.OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker arg0, int arg1, int arg2) {
						
					}
				}, 0, 0, true);

				dpd.show();
			}
		});*/

        bt_query_video.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                byte[] szCameraId = null;
                try {
                    szCameraId = channelId.getBytes("utf-8");
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                int nRet = 0;
                String strRet = "";
                Return_Value_Info_t nRecordCount = new Return_Value_Info_t();
                Query_Record_Info_t queryRecordInfo = new Query_Record_Info_t();
                System.arraycopy(szCameraId, 0, queryRecordInfo.szCameraId, 0, szCameraId.length);
                queryRecordInfo.nRight = 0;
                queryRecordInfo.nRecordType = 0;
                queryRecordInfo.nSource = m_nRecordSource;

					/*Calendar startCalendar = Calendar.getInstance();
					startCalendar.set(dp_start_date.getYear(), dp_start_date.getMonth(), dp_start_date.getDayOfMonth(), tp_start_time.getCurrentHour(), tp_start_time.getCurrentMinute(), 0);
					Calendar endCalendar = Calendar.getInstance();
					endCalendar.set(dp_end_date.getYear(), dp_end_date.getMonth(), dp_end_date.getDayOfMonth(), tp_end_time.getCurrentHour(), tp_end_time.getCurrentMinute(), 0);		*/
                if (startCalendar != null) {
                    queryRecordInfo.uBeginTime = startCalendar.getTimeInMillis() / 1000;
                }
                if (endCalendar != null) {
                    queryRecordInfo.uEndTime = endCalendar.getTimeInMillis() / 1000;
                }


                nRet = IDpsdkCore.DPSDK_QueryRecord(m_pDLLHandle, queryRecordInfo, nRecordCount, 10 * 1000);

                int nCount = nRecordCount.nReturnValue;

                if (0 == nRet) {

                    Record_Info_t records = new Record_Info_t(nCount);

                    try {
                        records.szCameraId = channelId.getBytes("utf-8");
                        m_RecordFileInfo.szCameraId = channelId.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    records.nBegin = 0;

                    IDpsdkCore.DPSDK_GetRecordInfo(m_pDLLHandle, records);

                    if (records.nCount > 0) {
                        m_RecordFileInfo.nFileIndex = records.pSingleRecord[0].nFileIndex;
                        m_RecordFileInfo.nMode = 1;
                        m_RecordFileInfo.nRight = 0;
                        m_RecordFileInfo.uBeginTime = records.pSingleRecord[0].uBeginTime;
                        m_RecordFileInfo.uEndTime = records.pSingleRecord[0].uEndTime;
                    }
                }

            }
        });

        bt_playback_file.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (!StartRealPlay()) {
                    Log.e("xss", "StartRealPlay failed!");
                    return;
                }

                //		Return_Value_Info_t nPlaybackSeq = new Return_Value_Info_t();
                int nRet = IDpsdkCore.DPSDK_GetRecordStreamByFile(m_pDLLHandle, m_nPlaybackSeq, m_RecordFileInfo, fm, 20 * 1000);

                if (nRet == 0) {
                    Log.e("xss", "DPSDK_GetRecordStreamByFile success!");
                } else {
                    Log.e("xss", "DPSDK_GetRecordStreamByFile failed!");
                }

            }
        });

        bt_playback_time.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!StartRealPlay()) {
                    Log.e("xss", "StartRealPlay failed!");
                    return;
                }

//	 				Return_Value_Info_t nPlaybackSeq = new Return_Value_Info_t();

                int nRet = 0;

                Get_RecordStream_Time_Info_t getRecordStreamTimeInfo = new Get_RecordStream_Time_Info_t();
                try {
                    getRecordStreamTimeInfo.szCameraId = channelId.getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                getRecordStreamTimeInfo.nMode = 1;
                getRecordStreamTimeInfo.nRight = 0;
                getRecordStreamTimeInfo.nSource = m_nRecordSource;

					/*Calendar startCalendar = Calendar.getInstance();
					startCalendar.set(dp_start_date.getYear(), dp_start_date.getMonth(), dp_start_date.getDayOfMonth(), tp_start_time.getCurrentHour(), tp_start_time.getCurrentMinute(), 0);
					Calendar endCalendar = Calendar.getInstance();
					endCalendar.set(dp_end_date.getYear(), dp_end_date.getMonth(), dp_end_date.getDayOfMonth(), tp_end_time.getCurrentHour(), tp_end_time.getCurrentMinute(), 0);	*/
                getRecordStreamTimeInfo.uBeginTime = startCalendar.getTimeInMillis() / 1000;
                getRecordStreamTimeInfo.uEndTime = endCalendar.getTimeInMillis() / 1000;

                nRet = IDpsdkCore.DPSDK_GetRecordStreamByTime(m_pDLLHandle, m_nPlaybackSeq, getRecordStreamTimeInfo, fm, 40 * 1000);

                if (nRet == 0) {
                    Log.e("xss", "DPSDK_GetRecordStreamByTime success!");
                } else {
                    Log.e("xss", "DPSDK_GetRecordStreamByTime failed!");
                }
            }
        });


        bt_playback_close.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                int nPlaybackReq = m_nPlaybackSeq.nReturnValue;
                int ret = IDpsdkCore.DPSDK_CloseRecordStreamBySeq(m_pDLLHandle, nPlaybackReq, 10 * 1000);
                if (ret == 0) {
                    Log.e("xss", "DPSDK_CloseRecordStreamBySeq success!");
                } else {
                    Log.e("xss", "DPSDK_CloseRecordStreamBySeq failed!");
                }
                StopRealPlay();
            }
        });

    }

    public void StopRealPlay() {
        try {
            IPlaySDK.PLAYStopSoundShare(m_nPort);
            IPlaySDK.PLAYStop(m_nPort);
            IPlaySDK.PLAYCloseStream(m_nPort);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean StartRealPlay() {
        if (m_svPlayer == null)
            return false;

        boolean bOpenRet = IPlaySDK.PLAYOpenStream(m_nPort, null, 0, 1500 * 1024) == 0 ? false : true;
        if (bOpenRet) {
            boolean bPlayRet = IPlaySDK.PLAYPlay(m_nPort, m_svPlayer) == 0 ? false : true;
            if (bPlayRet) {
                boolean bSuccess = IPlaySDK.PLAYPlaySoundShare(m_nPort) == 0 ? false : true;
                if (!bSuccess) {
                    IPlaySDK.PLAYStop(m_nPort);
                    IPlaySDK.PLAYCloseStream(m_nPort);
                    return false;
                }
            } else {
                IPlaySDK.PLAYCloseStream(m_nPort);
                return false;
            }
        } else {
            return false;
        }

        return true;
    }

    private void makeSpinner() {

        Resources res = getResources();
        String[] spType = {"0 全部录像","1 手动录像","2 报警录像",">3 移动侦测","4 视频丢失","5 视频遮挡","6 定时录像","7 全天录像","25 卡号录像"};
        String[] spSource = {"2 设备录像","3 平台录像"};
        String[] spSize = {"1 1/8倍","2 1/4倍","4 1/2倍","8 1倍","16 2倍","32 4倍","48 6倍","64 8倍"};
        ArrayAdapter<String> aaType = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, spType);
        //改变字体颜色
        aaType.setDropDownViewResource(getResources()
                .getIdentifier("spinner_item", "id",getPackageName()));

        ArrayAdapter<String> aaSource = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, spSource);
        aaSource.setDropDownViewResource(getResources()
                .getIdentifier("spinner_item", "id",getPackageName()));

        ArrayAdapter<String> aaSize = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, spSize);
        aaSize.setDropDownViewResource(getResources()
                .getIdentifier("spinner_item", "id",getPackageName()));

        Spinner spinnerType = (Spinner) findViewById(getResources()
                .getIdentifier("sp_video_type", "id",getPackageName()));
        Spinner spinnerSource = (Spinner) findViewById(getResources()
                .getIdentifier("sp_source", "id",getPackageName()));
//      Spinner spinnerSize = (Spinner)rootView.findViewById(R.id.sp_video_rate);
        spinnerType.setAdapter(aaType);
        spinnerSource.setAdapter(aaSource);
        spinnerSource.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                if (0 == arg2) {
                    m_nRecordSource = 2;
                    Log.d("xss:", "record source:" + arg2);
                } else {
                    m_nRecordSource = 3;
                    Log.d("xss:", "record source:" + arg2);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

//        spinnerSize.setAdapter(aaSize);


    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

}
